package com.tosh;

import com.tosh.model.Film;
import com.tosh.model.Names;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * User: arsentyev
 * Date: 13.12.12
 */
public class Parser {
    private final static Logger _log = Logger.getLogger(Parser.class.getName());
    private static final XMLInputFactory _fac = XMLInputFactory.newInstance();
//    private static final XMLInputFactory _fac = WstxInputFactory.newInstance();

    public static void parse(String xml) {
        XMLEventReader reader = null;
        String elemName = null;
        Attribute attribute = null;
        QName qid = new QName("id");
        List<Film> films = new ArrayList<Film>();
        Film film = null;
        long id = 1;
        int year = -1;
        String url = null, picture = null, description = null, country = null, rusName = null, origName = null, starring = null, director = null;

        try {
            reader = _fac.createXMLEventReader(new StringReader(xml));

            while (reader.hasNext()) {
                XMLEvent event = reader.nextEvent();

                if (event.getEventType() == XMLEvent.START_ELEMENT) {
                    StartElement startElement = event.asStartElement();
                    elemName = startElement.getName().getLocalPart();

                    switch (Names.getByName(elemName)) {
                        case OFFER: {
                            film = new Film();
                            attribute = startElement.getAttributeByName(qid);
                            id = Long.parseLong(attribute.getValue());
                            film.setId(id);
                            break;
                        }
                        case URL: {
                            event = reader.nextEvent();
                            url = event.asCharacters().getData();
                            break;
                        }
                        case PICTURE: {
                            event = reader.nextEvent();
                            picture = event.asCharacters().getData();
                            break;
                        }
                        case DESCRIPTION: {
                            event = reader.nextEvent();
                            description = event.asCharacters().getData();
                            break;
                        }
                        case DIRECTOR: {
                            event = reader.nextEvent();
                            director = event.asCharacters().getData();
                            break;
                        }
                        case ORIGINALNAME: {
                            event = reader.nextEvent();
                            origName = event.asCharacters().getData();
                            break;
                        }
                        case TITLE: {
                            event = reader.nextEvent();
                            rusName = event.asCharacters().getData();
                            break;
                        }
                        case STARRING: {
                            event = reader.nextEvent();
                            starring = event.asCharacters().getData();
                            break;
                        }
                        case YEAR: {
                            event = reader.nextEvent();
                            year = Integer.parseInt(event.asCharacters().getData());
                            break;
                        }
                        case COUNTRY: {
                            event = reader.nextEvent();
                            country = event.asCharacters().getData();
                            break;
                        }
                    }
                }

                if (event.getEventType() == XMLEvent.END_ELEMENT) {
                    elemName = event.asEndElement().getName().getLocalPart();

                    switch (Names.getByName(elemName)) {
                        case OFFER: {
                            if(film != null) {
                                //film.setId(id);
                                film.setCountry(country);
                                film.setDescription(description);
                                film.setDirector(director);
                                film.setOrigName(origName);
                                film.setRusName(rusName);
                                film.setPicture(picture);
                                film.setStarring(starring);
                                film.setUrl(url);
                                film.setYear(year);

                                films.add(film);
                                film = null;
                            }
                            break;
                        }
                    }
                }
            }
        } catch (XMLStreamException e) {
            _log.severe(e.getMessage());
        }

        films.size();
    }

    public static List<Film> parse(InputStream is) {
        XMLEventReader reader = null;
        String elemName = null;
        Attribute attribute = null;
        QName qid = new QName("id");
        List<Film> films = new ArrayList<Film>();
        Film film = null;
        long id = 1;
        int year = -1;
        String url = null, picture = null, description = null, country = null, rusName = null, origName = null, starring = null, director = null;

        try {
            reader = _fac.createXMLEventReader(is);

            while (reader.hasNext()) {
                XMLEvent event = reader.nextEvent();

                if (event.getEventType() == XMLEvent.START_ELEMENT) {
                    StartElement startElement = event.asStartElement();
                    elemName = startElement.getName().getLocalPart();

                    switch (Names.getByName(elemName)) {
                        case OFFER: {
                            film = new Film();
                            attribute = startElement.getAttributeByName(qid);
                            id = Long.parseLong(attribute.getValue());
                            film.setId(id);
                            break;
                        }
                        case URL: {
                            event = reader.nextEvent();
                            url = event.asCharacters().getData();
                            break;
                        }
                        case PICTURE: {
                            event = reader.nextEvent();
                            picture = event.asCharacters().getData();
                            break;
                        }
                        case DESCRIPTION: {
                            event = reader.nextEvent();
                            description = event.asCharacters().getData();
                            break;
                        }
                        case DIRECTOR: {
                            event = reader.nextEvent();
                            director = event.asCharacters().getData();
                            break;
                        }
                        case ORIGINALNAME: {
                            event = reader.nextEvent();
                            origName = event.asCharacters().getData();
                            break;
                        }
                        case TITLE: {
                            event = reader.nextEvent();
                            rusName = event.asCharacters().getData();
                            break;
                        }
                        case STARRING: {
                            event = reader.nextEvent();
                            starring = event.asCharacters().getData();
                            break;
                        }
                        case YEAR: {
                            event = reader.nextEvent();
                            year = Integer.parseInt(event.asCharacters().getData());
                            break;
                        }
                        case COUNTRY: {
                            event = reader.nextEvent();
                            country = event.asCharacters().getData();
                            break;
                        }
                    }
                }

                if (event.getEventType() == XMLEvent.END_ELEMENT) {
                    elemName = event.asEndElement().getName().getLocalPart();

                    switch (Names.getByName(elemName)) {
                        case OFFER: {
                            if(film != null) {
                                //film.setId(id);
                                film.setCountry(country);
                                film.setDescription(description);
                                film.setDirector(director);
                                film.setOrigName(origName);
                                film.setRusName(rusName);
                                film.setPicture(picture);
                                film.setStarring(starring);
                                film.setUrl(url);
                                film.setYear(year);

                                films.add(film);
                                film = null;
                            }
                            break;
                        }
                    }
                }
            }
        } catch (XMLStreamException e) {
            _log.severe(e.getMessage());
        }

        return films;
    }

    public static List<Film> parse1(InputStream is) {
        XMLEventReader reader = null;
        String elemName = null;
        Attribute attribute = null;
        QName qid = new QName("id");
        List<Film> films = new ArrayList<Film>();
        Film film = null;
        long id = 1;
        String data = null;

        try {
            reader = _fac.createXMLEventReader(is);

            while (reader.hasNext()) {
                XMLEvent event = reader.nextEvent();

                switch (event.getEventType()) {
                    case XMLEvent.START_ELEMENT : {
                        StartElement startElement = event.asStartElement();
                        elemName = startElement.getName().getLocalPart();
                        switch (Names.getByName(elemName)) {
                            case OFFER: {
                                film = new Film();
                                films.add(film);
                                attribute = startElement.getAttributeByName(qid);
                                id = Long.parseLong(attribute.getValue());
                                film.setId(id);
                                break;
                            }
                        }
                        break;
                    }

//                    case XMLEvent.END_ELEMENT : {
//                        elemName = event.asEndElement().getName().getLocalPart();
//                        switch (Names.getByName(elemName)) {
//                            case OFFER: {
//                                if(film != null) {
//                                    //film.setId(id);
//                                    film.setCountry(country);
//                                    film.setDescription(description);
//                                    film.setDirector(director);
//                                    film.setOrigName(origName);
//                                    film.setRusName(rusName);
//                                    film.setPicture(picture);
//                                    film.setStarring(starring);
//                                    film.setUrl(url);
//                                    film.setYear(year);
//
//                                    films.add(film);
//                                    film = null;
//                                }
//                                break;
//                            }
//                        }
//                        break;
//                    }

                    case XMLEvent.CHARACTERS : {
                        data = event.asCharacters().getData().trim();
                        if(data.isEmpty()) {
                            continue;
                        }
                        if(film == null) {
                            film = new Film();
                        }

                        switch (Names.getByName(elemName)) {
                            case URL: {
                                film.setUrl(data);
                                break;
                            }
                            case PICTURE: {
                                film.setPicture(data);
                                break;
                            }
                            case DESCRIPTION: {
                                film.setDescription(data);
                                break;
                            }
                            case DIRECTOR: {
                                film.setDirector(data);
                                break;
                            }
                            case ORIGINALNAME: {
                                film.setOrigName(data);
                                break;
                            }
                            case TITLE: {
                                film.setRusName(data);
                                break;
                            }
                            case STARRING: {
                                film.setStarring(data);
                                break;
                            }
                            case YEAR: {
                                try {
                                    film.setYear(Integer.parseInt(data));
                                } catch (Exception e) {
                                    _log.severe(e.getMessage());
                                }
                                break;
                            }
                            case COUNTRY: {
                                film.setCountry(data);
                                break;
                            }
                        }
                    }
                }
            }
        } catch (XMLStreamException e) {
            _log.severe(e.getMessage());
        }

        return films;
    }
}

/*

milm_id - остается пустым, потом будем проставлять соответствия с _films по полю imdb_key
ozone_id = id3
url = url4
picture = picture
original_name = original name
russian_name = title
year = year
starring = starring
director = director
country = country
description = description



<offer id="3305648" type="artist.title" available="true">
        <url>http://www.ozon.ru/context/detail/id/3305648/?from=prt_xml_facet</url>
        <price>99</price>
        <currencyId>RUR</currencyId>
        <categoryId>1133211</categoryId>
        <categoryId>1133199</categoryId>
        <picture>http://www.ozon.ru/multimedia/video_dvd_covers/1000528789.jpg</picture>
        <delivery>true</delivery>
        <orderingTime>
          <ordering>На складе</ordering>
        </orderingTime>
        <title>Эскорт 3</title>
        <year>1999</year>
        <media>DVD</media>
        <starring>Джули Стрэйн, Тим Абель, Лэндон Холл, Роберт Донован, Росс Хаген</starring>
        <director>Том Попатолоус</director>
        <originalName>The Escort III</originalName>
        <country>США</country>
        <description>Джули Стрэйн ("Звездная болезнь"), Росс Хаген ("Остров динозавров"), Тим Абель ("Быстрое реагирование") в саспенс триллере Тома Попатолоуса "Эскорт 3". После загадочного убийства деловой красавицы Джули Кларк основным подозреваемым становится ее коллега, молодой архитектор Джим Корриган. Бывалый детектив Грабовский упрямо выведывает тайны его личной жизни и вскоре узнаёт, что этот хладнокровный бизнесмен был завсегдатаем элитной фирмы эскорт-услуг, в которой подрабатывала Джули. Петля на шее Джима начинает затягиваться, когда полиция узнаёт о его хитрых финансовых аферах и ссоре с Джули, но внезапно железную версию следствия разрушает жестокое убийство Джима. Теперь только опытный Крэйг Грабовский сможет узнать, кому перешли дорогу Джули и Джим, поплатившись за это своей жизнью.</description>
        <barcode>4607087679134</barcode>
      </offer>

*/